<template>
  <div :style="{ height: `${docHeight}px`,backgroundColor: `${style.backgroundColor}` }" class="Doc">
    <div style="width:100%">
      <StatusBar @styleChange="(val) => {style = val}" :style="{ backgroundColor: `${style.backgroundBarColor}`}" :_style="style"></StatusBar>
    </div>
    <div class="docBody">
      <div style="width: 17%" :style="{height: `${docHeight - 28}px`, backgroundColor: `${style.backgroundNavColor}`}">
        <Catalog :_style="style" :list="docList" :selectIndex="selectDocIndex" @updateList="updateList" @select="selectComponent"></Catalog>
      </div>
      <div style="width: 83%">
        <!-- 参数控制 -->
        <div style="height: 240px;overflow-y: auto;" :style="{ backgroundColor: `${style.backgroundTopColor}`}">
          <Panel :docItem="docList[selectDocIndex]" :docFormData="docFormData2" @valueChange="PanelValueChange"></Panel>
        </div>
        <div class="doc-d-flex doc-pa-2 doc-flex-row" style="overflow: auto;" :style="{ width: `100%`,height: `${docHeight - 268}px`, backgroundColor: `#344A5F`}">
          <!-- <h3 style="color: #808F92">{{ docList[selectDocIndex].name }}</h3> -->
          <!-- <div class="docListCard" :style="{height: `100%`, width: `250px`,backgroundColor: `${style.docListbackgroundColor}`, marginRight: '10px'}">
            交互
          </div> -->
          <div  class="docListCard" :style="{height: `${docHeight / style.docListScaling}px`, width: `${docWidth / style.docListScaling}px`,backgroundColor: `${style.docListbackgroundColor}`}">
            <component
              v-if="isDocCom"
              :ref="`docCom`"
              v-bind="docFormData"
              :is="docList[selectDocIndex].componentName"
            ></component>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
/* eslint-disable no-unused-vars */
import Vue from "vue";
import utils from './public/js/utils'
import StatusBar from "./component/StatusBar.vue";
import Catalog from "./component/Catalog.vue";
import Panel from "./component/Panel.vue";
import FileSaver from './public/js/FileSaver';
let componentsArr = [],viewsArr = [];
export default {
  components: { StatusBar, Catalog, Panel },
  beforeCreate() {
    if(localStorage.getItem('docListbackgroundColor') === null) localStorage.setItem('docListbackgroundColor', '#1D2935');
    if(localStorage.getItem('docListScaling') === null) localStorage.setItem('docListScaling', 1);
    // const files = require.context(`@/components`, true, /.vue$/);
    // /^(?!.*(?:internals|system|TTitle.vue$)).*\.vue$/
    const files = require.context(`@/components`, true, /^(?!.*(?:internals|docShield|auto-vue-doc$)).*\.vue$/);
    files.keys().forEach((element, index) => {
      const url = "components/" + element.substring(2);
      let urlArr = element.split("/");
      let urlArrLen = urlArr[urlArr.length - 1];
      const name = urlArrLen.substring(0, urlArrLen.length - 4);
      Vue.component(`components-${name}-${index + 1}`, (resolve) => {
        require([`@/${url}`], resolve);
      });
      componentsArr.push({
        id: index + 1,
        name: name,
        url: url,
        index: index,
        componentName: `components-${name}-${index + 1}`,
        component: require(`@/${url}`).default
      })
    });
    const files2 = require.context(`@/views`, true, /^(?!.*(?:internals|docShield|auto-vue-doc$)).*\.vue$/);
    files2.keys().forEach((element, index) => {
      const url = "views/" + element.substring(2);
      let urlArr = element.split("/");
      let urlArrLen = urlArr[urlArr.length - 1];
      const name = urlArrLen.substring(0, urlArrLen.length - 4);
      Vue.component(`${name}${index + 1}`, (resolve) => {
        require([`@/${url}`], resolve);
      });
      viewsArr.push({
        id: index + 1,
        name: name,
        url: url,
        index: index,
        componentName: `views-${name}-${index + 1}`,
        component: require(`@/${url}`).default
      })
    });
  },
  data: () => ({
    selectIndex: 0,
    style: {
      backgroundBarColor: "#42B983",
      backgroundTopColor: "#C8EBDF",
      backgroundNavColor: '#FFFFFF',
      docListbackgroundColor: localStorage.getItem('docListbackgroundColor'),
      docListScaling: localStorage.getItem('docListScaling')
    },
    docList: [],
    isDocCom: true,
    docFormData: {}, // 组件标签传值
    docFormData2: {}, // 组件交互表单
    selectDocIndex: 0,
    searchVal: '',
    docHeight: document.documentElement.clientHeight,
    docWidth: document.documentElement.clientWidth
  }),
  created() {
    let mobileCode = undefined
    // let file = new File([mobileCode], "https://blog.faig.top/static/img/vuetify-logo-nodark-text.75c67061.svg", { type: "text/plain;charset=utf-8" });
    // FileSaver.saveAs("https://blog.faig.top/static/img/vuetify-logo-nodark-text.75c67061.svg", 'Hello.svg')
    // FileSaver.saveAs('', 'https://blog.faig.top/static/img/vuetify-logo-nodark-text.75c67061.svg')
    this.initComponents();
  },
  mounted() {
    window.onresize = () => {
      this.docHeight = document.documentElement.clientHeight
      this.docWidth = document.documentElement.clientWidth
    }
  },
  methods: {
    selectChange(){
      this.initComponents()
    },
    /**
     * 初始化组件
     */
    initComponents() {
      const files = [componentsArr, viewsArr][this.selectIndex]
      this.docList = []
      files.forEach(element => {
        let {id, name, url, index, componentName, component} = element
        let props = {}
        // 判断 props 是否存在
        if(component.props){
          props = component.props
          if(props.length){
            let tempProps = {}
            for (let index = 0; index < props.length; index++) {
              const element = props[index];
              tempProps[element] = {
                typex: 'Undefined',
                source: 'Array' // 记录该组件 props 写法
              }
            }
            props = tempProps
          } else {
            
            for(let key in props) {
              props[key].typex = 'Undefined'
              if(props[key].type){
                if(props[key].default && typeof props[key].default === 'function'){
                  props[key].defaultx = props[key].default()
                } else {
                  props[key].defaultx = props[key].default
                }
                props[key].typex = props[key].type.name
              } else {
                if(props[key] && typeof props[key] === 'function'){
                  const type = props[key]
                  props[key] = {}
                  props[key].type = type
                  props[key].typex = type.name
                  // props[key].defaultx = props[key]().default()
                }
              }
            }
          }
        }
        const quoteList = this.getComponentQuoteList(url)
        this.docList.push({
          id, name, index, componentName,
          url: component.__file,
          props: props,
          doc: component.doc ? component.doc : {},
          quoteList,
          quoteb: (quoteList.length / viewsArr.length * 100).toFixed(2)
        });
      })
      setTimeout(() => {this.selectComponent(0)}, 1)
    },
    /**
     * 获取组件引用
     */
    getComponentQuoteList(url){
      let res = [];
      viewsArr.forEach((element, index) => {
        if(element.component.components){
          let components = element.component.components
          for(let key in components){
            if(components[key].__file === 'src/' + url) res.push(element)
          }
        }
      })
      return res
    },
    /**
     * 切换选中组件
     */
    selectComponent(index){
      this.selectDocIndex = index
      let docCom = this.$refs.docCom
      let props = this.docList[this.selectDocIndex].props
      this.docFormData = {}
      this.docFormData2 = {}
      for(let key in props){
        let prop = props[key]
        this.docFormData[key] = props[key].defaultx
        this.docFormData2[key] = props[key].defaultx
        if(prop.typex === 'Object' || prop.typex === 'Array'){
          this.docFormData2[key] = JSON.stringify(props[key].defaultx)
        }
      }
      
     
    },
    /**
     * 修改集合
     */
    updateList(list){
      this.selectDocIndex = 0
      if(list){
        this.docList = list
      } else {
        this.initComponents()
      }
    },
    /**
     * 参数输入
     */
    PanelValueChange(formData){
      utils.refreshObj(this, 'isDocCom')
      let props = this.docList[this.selectDocIndex].props // 传递集合
      for(let key in props){
        this.docFormData[key] = this.conversionValue(formData[key], props[key])
      }
    },
    conversionValue(val, prop){
      if(prop.typex === 'Boolean'){
        if(val === 'false') val = false;
      } else if(prop.typex === 'Number'){
        val = Number(val)
      } else if(prop.typex === 'Function'){
        let funcStr = val;
        let test = eval("(false || "+funcStr+")");
        val = test
      } else if (prop.typex === 'Object' || prop.typex === 'Array' ) {
        val = JSON.parse(val)
      }
      return val
    }
  }
};
</script>
<style scoped>
@import './public/css/common.css';
.Doc {
  background-color: ：#dfdfdf;
  display: flex;
  flex-direction: column;
}
.docBody{
  display: flex;
  flex-direction: row;
}


.docListCard{
  border-radius: 6px;
}
</style>
